package top.soyask.bbs.utils;

import java.io.IOException;
import java.lang.reflect.Field;

import javax.servlet.http.HttpServletRequest;

import top.soyask.bbs.controller.base.BaseController;
import top.soyask.bbs.service.IHandleService;
import top.soyask.bbs.service.INoteService;
import top.soyask.bbs.service.IUserInfoService;
import top.soyask.bbs.service.imp.HandleService;
import top.soyask.bbs.service.imp.NoteService;
import top.soyask.bbs.service.imp.UserInfoService;

public class ControllerCreator {

//	private Logger logger = Logger.getLogger(getClass().getName());
	private static ControllerCreator creator = new ControllerCreator();

	private ControllerCreator() {
	}

	public static ControllerCreator getCreator() {
		return creator;
	}

	public synchronized BaseController getController(HttpServletRequest request, String className)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
		Class<?> clazz = Class.forName(className);
		BaseController controller = (BaseController) clazz.newInstance();
		Field.setAccessible(clazz.getDeclaredFields(), false);
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			String value = request.getParameter(field.getName());
			field.setAccessible(true);
			field.set(controller, cast(field.getType(), value));
		}
		return controller;
	}

	@SuppressWarnings("unchecked")
	public <T> T cast(Class<?> clazz, Object obj) throws InstantiationException, IllegalAccessException {

		String str = obj == null ? "-1" : obj.toString();

		if (clazz.equals(Integer.class) || clazz.equals(int.class)) {
			return (T) Integer.valueOf(str);
		} else if (clazz.equals(String.class) || clazz.equals(int.class)) {
			return (T) str;
		} else if (clazz.equals(Byte.class) || clazz.equals(byte.class)) {
			return (T) Byte.valueOf(str);
		} else if (clazz.equals(Character.class) || clazz.equals(char.class)) {
			return (T) Character.valueOf(str.charAt(0));
		} else if (clazz.equals(Short.class) || clazz.equals(short.class)) {
			return (T) Short.valueOf(str);
		} else if (clazz.equals(Long.class) || clazz.equals(long.class)) {
			return (T) Long.valueOf(str);
		} else if (clazz.equals(Double.class) || clazz.equals(double.class)) {
			return (T) Double.valueOf(str);
		} else if (clazz.equals(Float.class) || clazz.equals(float.class)) {
			return (T) Float.valueOf(str);
		} else if (clazz.equals(IHandleService.class)) {
			return (T) new HandleService();
		} else if (clazz.equals(INoteService.class)) {
			return (T) new NoteService();
		} else if (clazz.equals(IUserInfoService.class)) {
			return (T) new UserInfoService();
		}
		return null;
	}

}
